﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DslamPort.Models;
using System.Web.Security;
namespace DslamPort.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
                ViewBag.status = false;
            else
                ViewBag.status = true;
            return View();
        }
        [HttpPost]
        public ActionResult Index(UserModel us, string returnUrl)
        {

            //var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                if (UserModel.IsValid(us.user_name, us.password) != 0 && us.user_name.IndexOf(' ') == -1 && us.password.IndexOf(' ') == -1)
                {
                    UserModel userModel = new UserModel();
                    List<UserModel> user = userModel.getUserByName(us.user_name);                   
                    foreach (UserModel u in user)
                    {
                        if (u.user_name == "admin")
                            Session["quyen"] = 0;
                        else
                            Session["quyen"] = 1;
                        Session["user_name"] = u.user_name;
                        Session["status"] = u.status;
                    }
                    FormsAuthentication.SetAuthCookie(us.user_name, us.RememberMe);                    
                    if (Session["status"].ToString() == "2")
                    {
                        return RedirectToAction("Index", "ManagerPort");
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            TempData["msg"] = "Tên đăng nhập hoặc mật khẩu không chính xác!";
            return RedirectToAction("Index");
            //return View(us);            

        }
        public ActionResult About()
        {
            return View();
        }
    }
}
